import { MessagePlugin } from 'tdesign-vue-next';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style

import { getMenusStore, getPermissionStore, getUserStore } from '@/store';
import router, { defaultRouterList } from "@/router";

NProgress.configure({ showSpinner: false });
const whiteList = ['/login']; // no redirect whitelist
const openPage = ['/verify', '/register']; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  NProgress.start();

  if (openPage.indexOf(to.path) !== -1) {
    // in the free login whitelist, go directly
    next();
    return;
  }

  const userStore = getUserStore();
  const permissionStore = getPermissionStore();
  const menusStore = getMenusStore();

  const { token } = userStore;
  if (token) {
    if (to.path === '/login') {
      next();
      return;
    }

    const { account } = userStore;
    if (account) {
      next();
    } else {
      try {
        await userStore.getUserInfo();
        await menusStore.getMenus();
        const { roles } = userStore;

        console.log('-->go', menusStore.menuList)

        await permissionStore.initRoutes(defaultRouterList.concat(menusStore.menuList));
        // 重写路由展示隐藏
       // router.options.routes = defaultRouterList.concat(menusStore.menuList);


        console.log('--to--',roles,  router.options.routes);

        if (router.hasRoute(to.name)) {
          next();
        } else {
          next(`/404`);
        }
      } catch (e) {
        console.log('------->', e.message);
        MessagePlugin.error(e.message);
        next({
          path: '/login',
          query: { redirect: encodeURIComponent(to.fullPath) },
        });
        NProgress.done();
      }
    }
  } else {
    /* white list router */
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next({
        path: '/login',
        query: { redirect: encodeURIComponent(to.fullPath) },
      });
    }
    NProgress.done();
  }
});

router.afterEach((to) => {
  if (to.path === '/login') {
    const userStore = getUserStore();
    //const permissionStore = getPermissionStore();

    userStore.logout();
   // permissionStore.restore();
  }
  NProgress.done();
});
